package transforms;

import java.util.ListIterator;

import org.apache.bcel.generic.ClassGen;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodNode;

import com.rshacking.rhf.files.ClassContainer;
import com.rshacking.rhf.updater.Transform;
import com.rshacking.rhf.updater.hooks.ClassHook;
import com.rshacking.rhf.updater.hooks.HooksList;
import com.rshacking.rhf.updater.instructions.InsnCondition;
import com.rshacking.rhf.updater.instructions.InstructionFinder;

public class NPCTransform extends Transform {

	@Override
	public boolean canActivate(HooksList hooks, ClassContainer cc) {
		return new ClassGen(cc.getBCEL()).getConstantPool().lookupUtf8(
				"gnp1 pos:") > 0;
	}

	@Override
	public boolean execute(HooksList hooks, ClassContainer cc) {

		ClassHook client = null;
		if (hooks.contains("Client"))
			client = hooks.get("Client");
		else
			client = hooks.add("Client", "client");
		ListIterator<?> i = cc.getASM().methods.listIterator();
		while (i.hasNext()) {
			MethodNode mn = (MethodNode) i.next();
			InstructionFinder<AbstractInsnNode> finder = new InstructionFinder<AbstractInsnNode>(
					mn, true);
			if (finder.getNext(InsnCondition.ASM.makeLDCCond("gnp1 pos:")) == null)
				continue;
			FieldInsnNode fin = null;
			fin = (FieldInsnNode) finder
					.getNext(InsnCondition.ASM.GETSTATIC_IA);
			if (fin != null)
				client.add("npcIndexArray", fin);
			finder.getNext(InsnCondition.ASM.makeLDCCond("gnp2 pos:"));
			fin = (FieldInsnNode) finder.getNext(InsnCondition.ASM.GETSTATIC_I);
			if (fin != null)
				client.add("npcCount", fin);
			finder.reset(true);
			fin = (FieldInsnNode) finder
					.getNext(InsnCondition.ASM.GETSTATIC_LA);
			if (fin != null) {
				hooks.add("NpcNode", fin.desc);
				client.add("npcArray", fin);
			}
			break;
		}
		return true;
	}

}